package com.qfedu.labsystem.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * @ClassName RSAConfig
 * @Author ykx
 * @Date 2024/4/19 12:25
 * @Version 1.0
 */
@Configuration
public class RSAConfig {

    private final String RSA = "RSA";
    private final Integer KEY_SIZE = 1024;

    @Bean
    public KeyPair getKeyPair() throws NoSuchAlgorithmException {
        // 1.获取公钥私钥
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(RSA);// 获取RSA算法实例
        keyPairGen.initialize(KEY_SIZE);// 1024代表密钥二进制位数
        return keyPairGen.generateKeyPair();// 产生KeyPair工厂
    }

    @Bean
    public RSAPublicKey getRSAPublicKey() throws NoSuchAlgorithmException {
        return (RSAPublicKey) getKeyPair().getPublic();
    }

    @Bean
    public RSAPrivateKey getRSAPrivateKey() throws NoSuchAlgorithmException {
        return (RSAPrivateKey) getKeyPair().getPrivate();
    }

    @Bean
    public Cipher getCipher() throws Exception {
        return Cipher.getInstance(RSA);
    }
}
